use crate::io::{InputDevice, OutputDevice};

/// 终端模拟器
pub struct Terminal {
    screen_buffer: Vec<char>,
    width: usize,
    height: usize,
    cursor_x: usize,
    cursor_y: usize,
}

impl Terminal {
    pub fn new(width: usize, height: usize) -> Self {
        Terminal {
            screen_buffer: vec![' '; width * height],
            width,
            height,
            cursor_x: 0,
            cursor_y: 0,
        }
    }

    fn update_cursor(&mut self) {
        self.cursor_x += 1;
        if self.cursor_x >= self.width {
            self.cursor_x = 0;
            self.cursor_y += 1;
            if self.cursor_y >= self.height {
                // 滚动屏幕
                self.screen_buffer.drain(0..self.width);
                self.screen_buffer.extend(vec![' '; self.width]);
                self.cursor_y = self.height - 1;
            }
        }
    }
}

impl OutputDevice for Terminal {
    fn write_char(&mut self, c: char) {
        let pos = self.cursor_y * self.width + self.cursor_x;
        if pos < self.screen_buffer.len() {
            self.screen_buffer[pos] = c;
            self.update_cursor();
        }
    }

    fn clear_screen(&mut self) {
        self.screen_buffer.fill(' ');
        self.cursor_x = 0;
        self.cursor_y = 0;
    }
}

impl InputDevice for Terminal {
    fn read_char(&mut self) -> Option<char> {
        // 终端输入将在平台特定代码中实现
        None
    }
}